package vip.xiaonuo.modular.front.blogcomment;

import cn.hutool.extra.mail.MailException;
import cn.hutool.log.Log;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.context.requestno.RequestNoContext;
import vip.xiaonuo.core.email.MailSender;
import vip.xiaonuo.core.email.modular.model.SendMailParam;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.exception.AuthException;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.exception.enums.AuthExceptionEnum;
import vip.xiaonuo.core.pojo.base.param.BaseParam;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.modular.blogcomment.entity.BlogComment;
import vip.xiaonuo.modular.blogcomment.param.BlogCommentParam;
import vip.xiaonuo.modular.blogcomment.service.BlogCommentService;
import vip.xiaonuo.modular.bloginfo.entity.BlogInfo;
import vip.xiaonuo.modular.bloginfo.service.BlogInfoService;
import vip.xiaonuo.modular.utils.SensitiveFilterUtil;
import vip.xiaonuo.sys.modular.email.enums.SysEmailExceptionEnum;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author liu
 */
@RestController
@RequestMapping("/front/blogComment")
public class FrontBlogCommentController {
    private static final cn.hutool.log.Log log = Log.get();
    @Resource
    private BlogCommentService blogCommentService;
    @Resource
    private BlogInfoService blogInfoService;

    @Lazy
    @Resource
    private CaptchaService captchaService;

    @Resource
    private MailSender mailSender;

    @Value("${SensitiveFilterFilePath}")
    private String path;


    @GetMapping("/count")
    public ResponseData count(BlogCommentParam blogCommentParam) {
        QueryWrapper<BlogComment> queryWrapper = new QueryWrapper<>();
        if (blogCommentParam.getBlogId() != null) {
            queryWrapper.lambda().eq(BlogComment::getCommentStatus, 1);
            queryWrapper.lambda()
                    .eq(BlogComment::getBlogId, blogCommentParam.getBlogId());
            return new SuccessResponseData(blogCommentService.count(queryWrapper));
        }
        return new SuccessResponseData(blogCommentService.count());
    }

    @GetMapping("/page")
    @BusinessLog(title = "评论_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData page(BlogCommentParam blogCommentParam, Boolean isParent) {
        blogCommentParam.setCommentStatus(1);
        return new SuccessResponseData(blogCommentService.page(blogCommentParam, isParent));
    }

    @GetMapping("/treePage")
    @BusinessLog(title = "评论_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData treePage(BlogCommentParam blogCommentParam) {
        PageResult<BlogComment> treePage = blogCommentService.getCommentTree(blogCommentParam);
        return new SuccessResponseData(treePage);
    }
    /*@GetMapping("/list")
    @BusinessLog(title = "评论_列表", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(BlogCommentParam blogCommentParam) {
        blogCommentParam.setCommentStatus(1);
        return new SuccessResponseData(blogCommentService.list(blogCommentParam));
    }*/

    @PostMapping("/add")
    @BusinessLog(title = "评论_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData add(@RequestBody @Validated({BlogCommentParam.add.class, BaseParam.verify.class}) BlogCommentParam blogCommentParam, HttpServletRequest req) {
        CaptchaVO vo = new CaptchaVO();
        vo.setCaptchaVerification(blogCommentParam.getCode());
        if (!captchaService.verification(vo).isSuccess()) {
            throw new AuthException(AuthExceptionEnum.CONSTANT_EMPTY_ERROR);
        }
        String filter = SensitiveFilterUtil.filter(blogCommentParam.getCommentBody(), path);
        if (filter.contains("*")) {
            return ResponseData.error("对不起，当前评论包含敏感词，请文明发言,勿发广告！");
        }
        BlogInfo one = blogInfoService.getOne(blogCommentParam.getBlogId().toString(), true);
        if(one == null){
            return ResponseData.error("对不起,此博客不存在");
        }
        if(one.getEnableComment()==1){
            return ResponseData.error("对不起,当前博客暂不允许评论");
        }
        BlogCommentParam param = new BlogCommentParam();
        param.setBlogId(blogCommentParam.getBlogId()).setCommentator(blogCommentParam.getCommentator())
                .setCommentBody(blogCommentParam.getCommentBody()).setEmail(blogCommentParam.getEmail())
                .setWebsiteUrl(blogCommentParam.getWebsiteUrl()).setParentId(blogCommentParam.getParentId())
                .setCommentatorIp(getIpAddress(req));
        param.setCommentStatus(1);

            sendMail(blogCommentParam);


        blogCommentService.add(param);


        return new SuccessResponseData();
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public void sendMail(BlogCommentParam blogCommentParam) {
        SendMailParam mailParam = new SendMailParam();
        String domain = ConstantContextHolder.getSysConfig("domain", String.class, false);
        String mailReceive = ConstantContextHolder.getSysConfig("MAIL_RECEIVE", String.class, false);
        mailParam.setTitle("收到评论留言，请及时查看");
        mailParam.setTo(mailReceive);
        mailParam.setContent("评论用户：" + blogCommentParam.getCommentator() + ";    评论内容：" + blogCommentParam.getCommentBody()
                + ";    评论博客网址：" + domain + "/article/" + blogCommentParam.getBlogId());
        try {
            mailSender.sendMail(mailParam);
        } catch (MailException e) {
            e.printStackTrace();
            log.error(">>> 邮件发送异常，请求号为：{}，具体信息为：{}", RequestNoContext.get(), e.getMessage());
            throw new ServiceException(SysEmailExceptionEnum.EMAIL_SEND_ERROR);
        }
    }
}
